package com.leilei.controller;

import com.leilei.MyObject.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.List;

/**
 * Created by yvdedu.com on 2016/10/21.
 */

@RestController
public class restController {

    static Map<String,String> codes=new HashMap<>();

    @RequestMapping(value = "/CheckCode",method = RequestMethod.GET,produces = MediaType.IMAGE_PNG_VALUE)
    public @ResponseBody
    byte[] chckCode(HttpServletResponse response,String id){
        response.setHeader("Pragma", "no-cache");
        String str = "0123456789abcdefghijklmnopqrstuvwxyz";
        String code="";
        int width=120;
        int height=46;
        int num=6;
        BufferedImage bufferedImage=new BufferedImage(width,height,BufferedImage.TYPE_4BYTE_ABGR);

        Graphics pen=bufferedImage.getGraphics();
        pen.setFont(new Font("微软雅黑",Font.PLAIN,height*2/3));
        Random random = new Random();
        for(int i=0;i<num;++i){
            int x = random.nextInt(15);
            int y = random.nextInt(15);
            int color = random.nextInt(0xffffff);
            int index =random.nextInt(str.length());
            String temp=str.substring(index,index+1);
            pen.setColor(new Color(color));
            pen.drawString(temp,x+i*width/num,height-y);
            code+=temp;
        }
        for(int i=0;i<num*2;++i){
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int dx = random.nextInt(width);
            int dy = random.nextInt(height);
            int color = random.nextInt(0xffffff);
            pen.setColor(new Color(color));
            pen.drawLine(x,y,dx,dy);
        }
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "png", bao);
            codes.put(id,code);
            new Thread(()->{
                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                codes.remove(id);
            }).start();
            return bao.toByteArray();
        } catch (IOException e) {
            return null;
        }
    }




    @RequestMapping("/codeCheck")
    public int codeChek(String code,String id){
        if (code.equals(codes.get(id))){
            return 1;
        }else {
            return 0;
        }
    }




    @RequestMapping("/CheckName")
    public boolean checkName(String name){
        if (name==null||name.isEmpty()||name.length()<6)return false;
        User user1 = controller.hibernate.getUser(name);
        if (user1==null){
            return true;
        }else {
            return false;
        }
    }




    @RequestMapping("/register")
    public boolean register(User user,String code,String cid){
        if (code.equals(codes.get(cid))){
            return controller.hibernate.saveUser(user);
        }else {
            return false;
        }
    }





    @RequestMapping("/login")
    public String login(User user,HttpSession session){
        User user1 = controller.hibernate.getUser(user.getName());
        if (user1!=null){
            if (user1.getPassWord().equals(user.getPassWord())){
                session.setAttribute("user",user1);
                return "true";
            }else {
                return "密码错误！";
            }
        }else {
            return "账号不存在！";
        }
    }





    @RequestMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }





    @RequestMapping("/saveArticle")
    public int saveArticle(Article article, int role, boolean top, HttpSession session){
        User user= (User) session.getAttribute("user");
        if (user==null)return 0;
        article.setUser(user);
        if (controller.hibernate.saveArticle(article,role,top))
        return article.getId();
        return 0;
    }




    @RequestMapping("/getArticleContent")
    public String getArticleContent(HttpSession session,String id){
        String content="";
        User user = (User) session.getAttribute("user");
        if (user==null)return content;
        try {
            if (id==null)throw new Exception("无效文章id");
            int Aid= Integer.parseInt(id);
            Article article = controller.hibernate.getArticle(Aid);
            User user1 = article.getUser();
            if (controller.hibernate.getRole(user.getId(),user1.getId())>article.getArticleInfo().getRole()){
                ObjectMapper objectMapper = new ObjectMapper();
                content=objectMapper.writeValueAsString(article);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return content;
    }

    @RequestMapping("/care")
    public String careUser(String id,HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null)return "noLogin";
        try {
            if (id==null)throw new Exception("无效用户id");
            int Uid= Integer.parseInt(id);
            User user1 = controller.hibernate.getUser(Uid);
            if (user1==null)return "noUser";
            if (controller.hibernate.caring(user.getId(), Uid)){
                controller.hibernate.noCareUser(user.getId(), Uid);
            }else {
                controller.hibernate.careUer(user.getId(), Uid);
            }
            if(controller.hibernate.caring(user.getId(), Uid)){
                return "care";
            }else {
                return "noCare";
            }
        }catch (Exception e){
            e.printStackTrace();
            return "noUser";
        }
    }

    @RequestMapping("/getUserInfo")
    public String getUserInfo(String id){
        if (id==null)return null;
        int Id= Integer.parseInt(id);
        User user = controller.hibernate.getUser(Id);
        if (user==null)return null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }



    @RequestMapping("/getMineInfo")
    public String getMineInfo(HttpSession session){
        User user = (User) session.getAttribute("user");
        if(user==null)return null;
        user = controller.hibernate.getUser(user.getId());
        if (user==null)return null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }





    @RequestMapping(value = "/userInfoUp",method = RequestMethod.POST)
    public String userInfoUp(MultipartFile file, UserInfo userInfo, HttpSession session){
        System.out.println(userInfo.getNickName());
        User user = (User) session.getAttribute("user");
        if (user==null)return "noLogin";
        userInfo.setPhoto(controller.hibernate.getUser(user.getId()).getUserInfo().getPhoto());
        userInfo.setUser(user);
        userInfo.setId(user.getId());
        String front="target/classes/static/";
        String name="photo/"+user.getName();
        if (!file.isEmpty()) {
            try {
                File temp=new File(front+name);
                System.out.println(temp.getAbsolutePath());
                if (!temp.getParentFile().exists())temp.getParentFile().mkdirs();
                if (temp.exists())temp.delete();
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(temp));
                stream.write(bytes);
                stream.close();
                userInfo.setPhoto(name);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            controller.hibernate.updateUserInfo(userInfo);
        }catch (Exception e){
            e.printStackTrace();
        }
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(controller.hibernate.getUser(user.getId()));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }






    @RequestMapping("/getFunsNum")
    public int getFunsNum(String id){
        try {
            if (id==null)throw new Exception("无效用户id");
            int Uid= Integer.parseInt(id);
            return controller.hibernate.getFunsNum(Uid);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }



    @RequestMapping("/isCare")
    public boolean isCare(String id,HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null)return false;
        try {
            if (id==null)throw new Exception("无效用户id");
            int Uid= Integer.parseInt(id);
            User user1 = controller.hibernate.getUser(Uid);
            if (user1==null)return false;
            return controller.hibernate.caring(user.getId(), Uid);
        }catch (Exception e ){
            e.printStackTrace();
            return false;
        }


    }

    @RequestMapping("/delArticle")
    public boolean delArticle(HttpSession session, String id){
        User user = (User) session.getAttribute("user");
        if (user==null)return false;
        try {
            if (id==null)throw new Exception("无效文章id");
            int Aid= Integer.parseInt(id);
            return controller.hibernate.delArticle(Aid);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    @RequestMapping("/remark")
    public boolean remark(Remark remark,int id,HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null)return false;
        remark.setUser(user);
        remark.setArticle(controller.hibernate.getArticle(id));
        return controller.hibernate.saveRemark(remark);
    }

    @RequestMapping("/getRemarkData")
    public String getRemarkData(String id,int page){
        if (id==null)return null;
        int Id= Integer.parseInt(id);
        java.util.List<Remark> remarkData = controller.hibernate.getRemarkData(Id,page);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(remarkData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
    @RequestMapping("/delRemark")
    public boolean delRemark(int id,HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null)return false;
        return controller.hibernate.delRemark(id,user.getId());
    }



    @RequestMapping("/getPrise")
    public String getPrise(String id, HttpSession session){
        if (id==null)return null;
        User user = (User) session.getAttribute("user");
        if (user==null)user=new User();
        int Id= Integer.parseInt(id);
        return controller.hibernate.get_prise_num(Id,user.getId());
    }
    @RequestMapping("/setPrise")
    public String setPrise(int id, HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null)user=new User();
        if (controller.hibernate.getPrise(id,user.getId())){
            controller.hibernate.delPrise(id,user.getId());
        }else {
            controller.hibernate.setPrise(id,user.getId());
        }
        return controller.hibernate.get_prise_num(id,user.getId());
    }


    @RequestMapping("/forward")
    public int forward(int id,HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null)return 0;
        Article article = controller.hibernate.getArticle(id);
        if (article==null)return 0;
        controller.hibernate.forward( user.getId(),id);
        if(controller.hibernate.getforward(id,user.getId())){
            List<Article> articles = controller.hibernate.getArticles( user.getId(),1);
            if (articles.size()>0){
                String name = article.getName();
                String content = article.getContent();
                Article article1 = articles.get(0);
                if (article1.getContent().equals(content)){
                    return 0;
                }else {
                    User user1 = controller.hibernate.getUser(user.getId());
                    Article article2 = new Article();
                    ArticleInfo articleInfo=new ArticleInfo();
                    articleInfo.setArticle(article2);
                    article2.setName(name+"（转自："+article.getUser().getUserInfo().getNickName()+"）");
                    article2.setContent(content);
                    article2.setUser(user1);
                    article2.setArticleInfo(articleInfo);
                    Article article3 = controller.hibernate.saveArticle(article2,articleInfo);
                    if (article3==null)return 0;
                    return article3.getId();
                }
            }
        }
        return 0;
    }



    @RequestMapping("/getMsgCode")
    public int getMsgCode(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null)return 0;
        int id = user.getId();
        int i = new Random().nextInt();
        websocket.userCode.put(id,i);
        return i;
    }


    @RequestMapping("/getFriends")
    public String getFriends(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user==null)return null;
        List<User> friends = controller.hibernate.getFriends(user.getId());
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(friends);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/getAllArticle")
    public String getAllArticle(int page,HttpSession session) throws JsonProcessingException {
        User user = (User) session.getAttribute("user");
        if(user==null){
            user=new User();
        }
        List<Article> articlesFromCare = controller.hibernate.getArticlesFromCare(user.getId(), page);
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(articlesFromCare);
        return s;
    }

    @RequestMapping("/getHotArticle")
    public String getHotArticle(int page ,HttpSession session) throws JsonProcessingException {
        User user = (User) session.getAttribute("user");
        if(user==null){
            user=new User();
        }
        List<Article> articlesFromCare = controller.hibernate.getArticleAtTodayUp(user.getId(), page);
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(articlesFromCare);
        return s;
    }

    @RequestMapping("/getUserArticle")
    public String getUserArticle(HttpSession session,int id,int page) throws JsonProcessingException {
        User user = (User) session.getAttribute("user");
        if (user==null){
            user=new User();
        }
        if(id==0){
            id=user.getId();
        }
        System.out.println("get");
        List<Article> articlesFromUser = controller.hibernate.getArticlesFromUser(user.getId(), id, page);
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(articlesFromUser);
        return s;
    }

    @RequestMapping("/getSearch")
    public String getSearch(String search,HttpSession session,int page) throws JsonProcessingException {
        User user = (User) session.getAttribute("user");
        if (user==null){
            user=new User();
        }
        List<Article> searchArticle = controller.hibernate.getSearchArticle(search, user.getId(), page);
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(searchArticle);
        return s;
    }

    @RequestMapping("/changePwd")
    public String tcp(HttpSession session,String oldPwd,String newPwd){
        User user = (User) session.getAttribute("user");
        if (user==null)return "请先登录";
        User user1 = controller.hibernate.getUser(user.getId());
        if(oldPwd.equals(user1.getPassWord())){
            return controller.hibernate.changePwd(user.getId(),newPwd)?"修改成功":"修改出错";
        }else {
            return "密码错误";
        }
    }
    @RequestMapping("/noUseUser")
    public String noUseUser(String id,HttpSession session){
        if (id==null)return "无效参数";
        User user = (User) session.getAttribute("user");
        if(controller.hibernate.isManager(user.getId())){
            int Id= Integer.parseInt(id);
            User user1 = controller.hibernate.getUser(Id);
            if(controller.hibernate.noUse(user1)){
                return user1.getUserInfo().getNickName()+"已经禁用";
            }
        }
        return "你没有权限";
    }

    @RequestMapping("/noUseArticle")
    public String noUseArticle(String id,HttpSession session){
        if (id==null)return "无效参数";
        User user = (User) session.getAttribute("user");
        if(controller.hibernate.isManager(user.getId())){
            int Id= Integer.parseInt(id);
            Article article = controller.hibernate.getArticle(Id);
            if(controller.hibernate.noUse(article)){
                return article.getName()+"已经禁用";
            }
        }
        return "你没有权限";
    }

}
